package java.Servlet;

import Service.EmailService;
import Service.UserService;
import org.json.JSONException;
import org.json.JSONObject;
import utils.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;

/**
 * @Author Su
 * @Date 2025/4/17 17:39
 * @Version 1.0 （版本号）
 */
@WebServlet("/api/auth/forgot-password")
public class ForgotPasswordServlet extends HttpServlet {

    private EmailService emailService;
    private UserService userService;

    @Override
    public void init() throws ServletException {
        try {
            Connection connection = DBUtil.getConnection();
            this.emailService = new EmailService(connection);
            this.userService = new UserService(connection);
        } catch (SQLException e) {
            throw new ServletException("初始化失败", e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        JSONObject responseJson = new JSONObject();

        try {
            // 1、解析请求体
            JSONObject requestJson = parseRequestBody(req);
            System.out.println(requestJson);
            String email = requestJson.getString("email");
            String type = requestJson.getString("type");
            // 2、判断邮箱是否存在
            boolean result = userService.isEmailRegistered(email);
            System.out.println("判断邮箱是否存在：" + result);
            if(!result){
                responseJson.put("code", 400);
                responseJson.put("message", "邮箱有误");
                return;
            }
            // 3、发送验证码
            Map<String, Object> map = emailService.codeGenAndSend(email, type);
            responseJson.put("code",map.get("code"));
            responseJson.put("message",map.get("message"));
        }  catch (JSONException e) {
            responseJson.put("code", 400);
            responseJson.put("message", "请求参数错误");
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } catch (SQLException e) {
            responseJson.put("code", 500);
            responseJson.put("message", "系统错误");
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            e.printStackTrace();
        } finally {
            resp.getWriter().print(responseJson.toString());
        }
    }

    private JSONObject parseRequestBody(HttpServletRequest req) throws IOException, JSONException {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = req.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }
        return new JSONObject(sb.toString());
    }
}
